package controller;

import clases.Curso;
import clases.Cursopractica;
import clases.Practica;
import clases.Usuario;
import codigos.Corregir_practicas;
import codigos.Subir_ficheros;
import controller.util.JsfUtil;
import controller.util.PaginationHelper;
import facades.PracticaFacade;
import java.io.IOException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.primefaces.model.UploadedFile;


@Named("practicaController")
@SessionScoped
public class PracticaController implements Serializable {

    private Curso asignatura;
    private Practica pr;
    @EJB
    private  facades.CursopracticaFacade ejbCursoPracticaFacade;

    private Practica current;
    private DataModel items = null;
    @EJB private facades.PracticaFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private UploadedFile fileP;
    private UploadedFile fileS;
    private UploadedFile fileC;

    public PracticaController() {
    }

    public Practica getSelected() {
        if (current == null) {
            current = new Practica();
            selectedItemIndex = -1;
        }
        return current;
    }

    private PracticaFacade getFacade() {
        return ejbFacade;
    }
    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem()+getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Practica)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Practica();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PracticaCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    
    public String create(Practica p){
        current = p;
        return create();
    }

    public String prepareEdit() {
        current = (Practica)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PracticaUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Practica)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PracticaDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count-1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex+1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Practica getPractica(java.lang.Integer id) {
        return ejbFacade.find(id);
    }
    
    // Codigo propio 
    
    public UploadedFile getFileP() {  
        return fileP;  
    }  
    
    public void setFileP(UploadedFile fileP) {  
        this.fileP = fileP;  
    }
    
    public UploadedFile getFileS() {  
        return fileS;  
    }  
    
    public void setFileS(UploadedFile fileS) {  
        this.fileS = fileS;  
    }
    
    public UploadedFile getFileC() {  
        return fileC;  
    }  
    
    public void setFileC(UploadedFile fileC) {  
        this.fileC = fileC;  
    }

    public Curso getAsignatura() {
        return asignatura;
    }

    public void setAsignatura(Curso asignatura) {
        this.asignatura = asignatura;
    }

    public Practica getPr() {
        return pr;
    }

    public void setPr(Practica pr) {
        this.pr = pr;
    }
    
    public void upload() throws IOException {
        Subir_ficheros sb = new Subir_ficheros();
        
        //Definimos las rutas
        String destino = "./../../../../../NetBeansProjects/Corrector_URJC/web/practicas/" + 
                asignatura.getAsignatura() + "/" + current.getNombre();
        String ruta = destino + "/practica/";
        //Establecemos la ruta principal
        current.setRuta(ruta);
        
        sb.upload(ruta,getFileP());
        ruta = destino +"/pruebas/";
        sb.upload(ruta,getFileC());
        ruta = destino +"/solucion/";
        sb.upload(ruta,getFileS());
        
        //Asignamos el objeto 'current' a una linea de la BBDD
        
        Practica aux = current;
        create();
        
        //Asociamos la practica a un curso
        Cursopractica cp = new Cursopractica();
        cp.setIdpracticafk(current);
        cp.setIdcrusofk(asignatura);
        ejbCursoPracticaFacade.create(cp);  
    }
    
    public void upload2(Usuario usr) throws IOException, InterruptedException {
        Subir_ficheros sb = new Subir_ficheros();
        String ruta = "./../../../../../NetBeansProjects/Corrector_URJC/web/practicas/"
                + asignatura.getAsignatura() + "/" + pr.getNombre() + "/alumnos/" + 
                usr.getIdperfilfk().getNombre() + " " + usr.getIdperfilfk().getApellido1() + 
                 " " + usr.getIdperfilfk().getApellido2() + "/";
        //System.out.println(ruta);
        sb.upload(ruta,getFileP());
        
        //y a corregir
        
        Corregir_practicas cp = new Corregir_practicas();
        cp.corregir(ruta,getFileP().getFileName());
    }
    
    public ArrayList<Practica> practicasNoExpiradas(Curso cr){
        return ejbFacade.practicaFechaNoExpiradaPorCurso(cr);        
    }
    
    public String obtenerPractica(Practica prac, Curso cur){
        //Asignamos las variables para que permanezcan en memoria mientras nos 
        //movemos entre las distintas vistas
        
        pr = prac;
        asignatura = cur;
        return "./SubirPracticaAlumno.xhtml";
    }
    
    public int alumnosPracticaEntregada(Practica pra){
        return ejbFacade.alumnosPracticaEntregada(pra).size();
    }
    
    public boolean practicaSubidaAlumno(Practica pra, Usuario usr){
        return ejbFacade.practicaSubidaAlumno(pra,usr);
    }

    // Codigo propio

    @FacesConverter(forClass=Practica.class)
    public static class PracticaControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PracticaController controller = (PracticaController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "practicaController");
            return controller.getPractica(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Practica) {
                Practica o = (Practica) object;
                return getStringKey(o.getIdpractica());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+Practica.class.getName());
            }
        }

    }

}